package cn.com.acca.ma.hibernate.impl;

import cn.com.acca.ma.pojo.SuccessRateOrPercentagePojo;
import oracle.jdbc.OracleCallableStatement;
import oracle.jdbc.OracleTypes;
import oracle.sql.ARRAY;
import oracle.sql.Datum;
import oracle.sql.STRUCT;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.jdbc.Work;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GetHeiKinAshiDownUpSuccessRateWorkImpl implements Work {

    private static Logger logger = LogManager.getLogger(
        GetHeiKinAshiDownUpSuccessRateWorkImpl.class);

    private String beginDate;
    private String endDate;
    private Integer dateNumber;
    private List<SuccessRateOrPercentagePojo> list = new ArrayList<SuccessRateOrPercentagePojo>();

    public GetHeiKinAshiDownUpSuccessRateWorkImpl() {
    }

    public GetHeiKinAshiDownUpSuccessRateWorkImpl(String beginDate, String endDate, Integer dateNumber, List<SuccessRateOrPercentagePojo> list) {
        this.beginDate = beginDate;
        this.endDate = endDate;
        this.dateNumber = dateNumber;
        this.list = list;
    }

    @Override
    public void execute(Connection connection) throws SQLException {
        DatabaseMetaData databaseMetaData=connection.getMetaData();
        Connection metaDataConnection=null;
        if(null!=databaseMetaData){
            metaDataConnection=databaseMetaData.getConnection();
        }
        OracleCallableStatement ocs=(OracleCallableStatement) metaDataConnection.prepareCall("{call PKG_MODEL_RECORD.FIND_H_K_A_DOWNUP_SUCCESS_RATE(?,?,?,?)}");
        ocs.setString(1, beginDate);
        ocs.setString(2, endDate);
        ocs.setInt(3, dateNumber);
        ocs.registerOutParameter(4, OracleTypes.ARRAY,"T_H_K_A_SUCCESS_RATE_ARRAY");
        ocs.execute();
        ARRAY array=ocs.getARRAY(4);
        Datum[] datas=(Datum[]) array.getOracleArray();
        if(null!=datas){
            for (int i = 0; i < datas.length; i++){
                if(datas[i]!=null&&((STRUCT) datas[i])!=null){

                    Datum[] boardResultAttributes = ((STRUCT) datas[i]).getOracleAttributes();
                    SuccessRateOrPercentagePojo successRateOrPercentagePojo = new SuccessRateOrPercentagePojo();
                    successRateOrPercentagePojo.setTransactionDate(boardResultAttributes[0].dateValue());
                    successRateOrPercentagePojo.setSuccessRateOrPercentage(boardResultAttributes[1].bigDecimalValue());
                    list.add(successRateOrPercentagePojo);
                }else{
                    logger.info("datas["+i+"] is null.");
                }
            }
        }
    }
}
